package com.ys.service.finance.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.ys.config.MyConfig;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.finance.TcwFinancesEventGroupsOp;
import com.ys.enume.RegionEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.finance.TcwFinancesEventGroupsOpService;
import com.ys.vo.ApiResponse;
import io.swagger.client.ApiException;
import io.swagger.client.api.DefaultApi;
import io.swagger.client.model.FinancialEventGroup;
import io.swagger.client.model.FinancialEventGroupList;
import io.swagger.client.model.ListFinancialEventGroupsPayload;
import io.swagger.client.model.ListFinancialEventGroupsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.threeten.bp.OffsetDateTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service("tcwFinancesEventGroupOpOpService")
public class TcwFinancesEventGroupsOpServiceImpl implements TcwFinancesEventGroupsOpService {

    private static Logger logger = LoggerFactory.getLogger(TcwFinancesEventGroupsOpServiceImpl.class);

    @Autowired
    private DiySqlMapper diySqlMapper;


    /**
     * 每天获取财务事件
     * @param jsonObject
     * @param startTimeStr
     * @param endTimeStr
     * @return
     */
    @Override
    public ApiResponse getGroupsOp(JSONObject jsonObject, String startTimeStr, String endTimeStr) throws Exception{
        logger.info("***********每天或者手动定时新增财务目录,店铺:"+jsonObject.get("sellerName").toString());
        ApiResponse apiResponse = new ApiResponse();

        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId(MyConfig.getAmazonLwaClientKey())
                .clientSecret(MyConfig.getAmazonLwaClientSecret())
                .refreshToken(jsonObject.get("refreshToken").toString())
                .endpoint(MyConfig.getAmazonLwaEndpoint())
                .build();

        DefaultApi api = new DefaultApi.Builder()
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .endpoint(jsonObject.get("amazonServiceUrl").toString())
                .build();
        try {
            boolean isTrue = true;
            String nextToken = null;
            ListFinancialEventGroupsResponse listFinancialEventGroupsResponse;
            ListFinancialEventGroupsPayload listFinancialEventGroupsPayload;
            FinancialEventGroupList financialEventGroupList;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            TcwFinancesEventGroupsOp tcwFinancesEventGroupOp;
            List<TcwFinancesEventGroupsOp> tcwFinancesEventGroupOpList = new ArrayList<>();
            while (isTrue) {
                //获取当前传入时间的财务事件
                listFinancialEventGroupsResponse =
                        api.listFinancialEventGroups(
                                null, OffsetDateTime.parse(endTimeStr), OffsetDateTime.parse(startTimeStr), nextToken);
                if (listFinancialEventGroupsResponse != null) {
                    listFinancialEventGroupsPayload = listFinancialEventGroupsResponse.getPayload();
                    //取出事件
                    financialEventGroupList = listFinancialEventGroupsPayload.getFinancialEventGroupList();
                    for (FinancialEventGroup financialEventGroup : financialEventGroupList) {
                        //ProcessingStatus = Closed  财务事件组的处理状态指示财务事件组的余额是否已结算。
                        if (!financialEventGroup.getProcessingStatus().equals("Closed")) {
                            continue;
                        }
                        //FundTransferStatus  	资金转账的状态 Failed 失败 Succeeded 成功 。
                        if (financialEventGroup.getProcessingStatus() != null && financialEventGroup.getFundTransferStatus() != null) {
                            if (financialEventGroup.getProcessingStatus().equals("Closed") && financialEventGroup.getFundTransferStatus().equals("Succeeded")) {

                                //新增财务事件
                                tcwFinancesEventGroupOp = new TcwFinancesEventGroupsOp();
                                tcwFinancesEventGroupOp.setFinancialEventGroupId(financialEventGroup.getFinancialEventGroupId());
                                tcwFinancesEventGroupOp.setCurrencyCode(financialEventGroup.getOriginalTotal().getCurrencyCode());
                                tcwFinancesEventGroupOp.setRegionCode(jsonObject.get("regionCode").toString());
                                tcwFinancesEventGroupOp.setShopName(jsonObject.get("vgsjc").toString());
                                tcwFinancesEventGroupOp.setCompanyID(jsonObject.get("vgsbm").toString());
                                tcwFinancesEventGroupOp.setStartDate(dateFormat.parse(financialEventGroup.getFinancialEventGroupStart()));
                                tcwFinancesEventGroupOp.setEndDate(dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()));
                                tcwFinancesEventGroupOp.setCurrencyAmount(financialEventGroup.getOriginalTotal().getCurrencyAmount());
                                if (financialEventGroup.getConvertedTotal() == null){
                                    tcwFinancesEventGroupOp.setConvertedTotal(financialEventGroup.getOriginalTotal().getCurrencyAmount());
                                    tcwFinancesEventGroupOp.setCurrency(financialEventGroup.getOriginalTotal().getCurrencyCode());
                                }else {
                                    tcwFinancesEventGroupOp.setConvertedTotal(financialEventGroup.getConvertedTotal().getCurrencyAmount());
                                    tcwFinancesEventGroupOp.setCurrency(financialEventGroup.getConvertedTotal().getCurrencyCode());
                                }
                                tcwFinancesEventGroupOpList.add(tcwFinancesEventGroupOp);
                            }
                        }
                    }
                    if (listFinancialEventGroupsPayload.getNextToken() != null){
                        nextToken = listFinancialEventGroupsPayload.getNextToken();
                    }else {
                        isTrue = false;
                    }
                }else {
                    isTrue = false;
                }

                //批量新增/删除
                int financesEventGroupsLength = tcwFinancesEventGroupOpList.size();
                int j = 0;
                while (financesEventGroupsLength > 50) {
                    diySqlMapper.deleteBatchFinancesEventGroupsOp(tcwFinancesEventGroupOpList.subList(j, j + 50));
                    diySqlMapper.insetBatchFinancesEventGroupsOp(tcwFinancesEventGroupOpList.subList(j, j + 50));
                    j = j + 50;
                    financesEventGroupsLength = financesEventGroupsLength - 50;
                }
                if (financesEventGroupsLength > 0) {
                    diySqlMapper.deleteBatchFinancesEventGroupsOp(tcwFinancesEventGroupOpList.subList(j, j + financesEventGroupsLength));
                    diySqlMapper.insetBatchFinancesEventGroupsOp(tcwFinancesEventGroupOpList.subList(j, j + financesEventGroupsLength));
                }
            }

        }catch (ApiException ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API定时获取亚马逊财务事件信息出错，具体错误信息为："+ex.getResponseBody());
        }
        return apiResponse;
    }
}
